package blue.webserver;

import org.zeromq.ZMQ;

/* Zmq Subscriber without bind. */
public class ZmqSubscriber{
	private ZMQ.Context zmq_ctx_;
	private ZMQ.Socket zmq_sock_;	
	private String port_;
	private String filter_;

	public ZmqSubscriber(String port, String filter){
        //  Prepare our context and publisher
        port_ = port;
        filter_ = filter;
        String endpoint = "tcp://localhost:"+port_;
        zmq_ctx_ = ZMQ.context(1);
        zmq_sock_ = zmq_ctx_.socket(ZMQ.SUB);
        zmq_sock_.connect(endpoint);
        //  Subscribe to zipcode, default is NYC, 10001
        System.out.println("Subscribe from "+endpoint);
        zmq_sock_.setReceiveTimeOut(5000);
        zmq_sock_.subscribe(filter_.getBytes(ZMQ.CHARSET));    
	}

	public String recvWithBlocking() {
		return zmq_sock_.recvStr();
	}
	
	public String recv(){
        return zmq_sock_.recvStr(ZMQ.DONTWAIT);
	}
}
